package cn.cupk.logsystem.log.observerPattern;

import cn.cupk.logsystem.log.Level;
import cn.cupk.logsystem.log.LogRecord;
import lombok.Getter;

import java.util.ArrayList;
import java.util.List;

public class Logger {
    @Getter
    private final String name;
    @Getter
    private Level level;
    private final List<Handler> handlers;

    public Logger(String name) {
        this.name = name;
        this.level = Level.ALL;
        this.handlers = new ArrayList<>();
    }

    public void setLevel(Level level) {
        this.level = level;
    }

    public void addHandler(Handler handler) {
        handlers.add(handler);
        System.out.println("Handler added: " + handler.getClass().getSimpleName()); // 调试信息
    }


    public void log(Level level, String message) {
        System.out.println("Attempting to log message at level " + level + ": " + message);
        if (this.level.ordinal() <= level.ordinal()) {
            for (Handler handler : handlers) {
                System.out.println("Processing handler: " + handler.getClass().getSimpleName());
                handler.publish(new LogRecord(level, message, name));
            }
        } else {
            System.out.println("Log level too low to process message: " + message);
        }
    }



    public void severe(String message) {
        log(Level.SEVERE, message);
    }

    public void warning(String message) {
        log(Level.WARNING, message);
    }

    public void info(String message) {
        log(Level.INFO, message);
    }

    public void config(String message) {
        log(Level.CONFIG, message);
    }

    public void fine(String message) {
        log(Level.FINE, message);
    }
}
